package com.jqb.webservice.handler;
import java.util.Set;
import javax.xml.namespace.QName;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPFault;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPMessage;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;
import javax.xml.ws.soap.SOAPFaultException;
import org.w3c.dom.Node;
/*服务器端 Handler*/
public class LicenceHandler implements SOAPHandler<SOAPMessageContext>{
	@Override
	public boolean handleMessage(SOAPMessageContext context) {
		//out为true表示发送消息,false表示接收消息
		Boolean out = (Boolean)context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
		try {
			SOAPMessage soapMsg = context.getMessage();
			SOAPEnvelope soapEnvelope = soapMsg.getSOAPPart().getEnvelope();
			SOAPHeader soapHeader = soapEnvelope.getHeader();
			SOAPBody soapBody = soapEnvelope.getBody();
			if(!out){
				//只对login()和addUser()两个方法做验证
				String method = soapBody.getChildNodes().item(0).getLocalName();
				if("login".equals(method)||"addUser".equals(method)){
					/*方式一*/
					if(soapHeader==null||!soapHeader.hasChildNodes()){
						System.out.println("没有请求头信息...");
						SOAPFault soapFault = soapBody.addFault();
						soapFault.setFaultString("验证失败...");
						throw new SOAPFaultException(soapFault);
					}else{
//						Node licence = soapHeader.getElementsByTagName("sx:licenceInfo").item(0);
						Node licence = soapHeader.getChildNodes().item(0);
						System.out.println("验证信息:"+licence.getTextContent());
					}
					
					/*方式二
					if(soapHeader==null){
						System.out.println("没有请求头信息...");
						SOAPFault soapFault = soapBody.addFault();
						soapFault.setFaultString("验证失败...");
						throw new SOAPFaultException(soapFault);
					}
					Iterator<SOAPHeader> iter = soapHeader.extractAllHeaderElements();
					if(!iter.hasNext()){
						System.out.println("请求头信息不正确...");
						SOAPFault soapFault = soapBody.addFault();
						soapFault.setFaultString("验证失败...");
						throw new SOAPFaultException(soapFault);
					}
					while(iter.hasNext()){
						SOAPHeader sh = iter.next();
						System.out.println("验证信息"+sh.getChildNodes().item(0).getTextContent());;
					}
					*/
				}
				
			}
		} catch (SOAPException e) {
			e.printStackTrace();
		}
		return true;
	}

	@Override
	public boolean handleFault(SOAPMessageContext context) {
		System.out.println("err");
		return false;
	}

	@Override
	public void close(MessageContext context) {
		
	}

	@Override
	public Set<QName> getHeaders() {
		return null;
	}

}
